package com.rock.code.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * test httppost
 *
 * @author zhangli
 * @version V1.0
 * @create 2019-02-16 14:11
 **/
public class ZabbixUtil {


    private static java.util.ResourceBundle LoginInfo = java.util.ResourceBundle.getBundle("zabbix");
    private static String URL = "http://192.168.1.143/zabbix/api_jsonrpc.php";

    private static long LAST_TIME = System.currentTimeMillis();

    private static String AUTH = null;

    private static String USERNAME = "admin";

    private static String PASSWORD = "zabbix";

    private static int RELOADTIME = Integer.parseInt(LoginInfo.getString("realtimerinterval"));

    static {
        URL = "http://" + LoginInfo.getString("zabbixserverip") + ":" + LoginInfo.getString("zabbixport") + LoginInfo.getString("zabbixapiurl");
        USERNAME = LoginInfo.getString("user");
        PASSWORD = LoginInfo.getString("pwd");


    }


    /***
     * @Author zhangli
     * @Description //TODO 指定时间初始化zabbix
     * @Date 16:00 2019/2/19
     * @Param []
     * @return void
     **/
    public static void initzabbix() {
        if (System.currentTimeMillis() - LAST_TIME > RELOADTIME) {
            URL = "http://" + LoginInfo.getString("zabbixserverip") + ":" + LoginInfo.getString("zabbixport") + LoginInfo.getString("zabbixapiurl");
            USERNAME = LoginInfo.getString("user");
            PASSWORD = LoginInfo.getString("pwd");
            LAST_TIME = System.currentTimeMillis();
        }


    }

    public static List getHost() {
        Map<String, Object> insterfaces = new HashMap<>();
        insterfaces.put("interfaces", "ip");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("selectInterfaces", "extend");//获取zabbix 的接口 ip 信息（接口ip就是监控的ip）
        params.put("output", "extend");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "host.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        JSONObject jsonParam = (JSONObject) JSON.toJSON(map);
        List hostList = new ArrayList();
        String response = HttpRequestUtils.httpPost(URL, jsonParam, false, false).toJSONString();
//        System.out.println(response);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");
        if (result.size() > 0) {
            for (int i = 0; i < result.size(); i++) {
//                String host = result.getJSONObject(i).getString("host") + " " + result.getJSONObject(i).getString("hostid");
                String ip = getIpFromHost(result.getJSONObject(i),result.getJSONObject(i).getString("hostid"));
                Map hostMap = new HashMap();
                hostMap.put("host", result.getJSONObject(i).getString("host"));
                hostMap.put("hostId", result.getJSONObject(i).getString("hostid"));
                hostMap.put(ip, result.getJSONObject(i).getString("hostid"));

                hostList.add(hostMap);
            }
        } else {
            return null;
        }
        return hostList;
    }

    public static String getIpFromHost(JSONObject json ,String hostId){
        JSONArray jsonArray = json.getJSONArray("interfaces");
        for (Object obj : jsonArray) {
            JSONObject _json = (JSONObject) obj;
            String ip =  String.valueOf(_json.get("ip"));
            return ip;
        }
        return null;
    }
    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Author zhangli
     * @Description //TODO 根据zabbixHostid 获取所有的监控项
     * @Date 17:09 2019/2/19
     * @Param [hostId]
     **/
    public static JSONArray getZabbixItemForHostId(String hostId) {
        Map<String, Object> filter = new HashMap<String, Object>();
        filter.put("hostid", hostId);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("history", 1);
        params.put("filter", filter);


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "item.get");
        map.put("params", params);
        map.put("auth", getAuth());

        map.put("id", 0);

        JSONObject jsonParam = (JSONObject) JSON.toJSON(map);
        JSONObject jsonObj = HttpRequestUtils.httpPost(URL, jsonParam, false, false);

        JSONArray jsonArray = jsonObj.getJSONArray("result");


        return jsonArray;

    }

    // 获取主机类型
    public static String getHostType(String hostId) {

        Map<String, Object> filter = new HashMap<String, Object>();
        filter.put("hostid", hostId);

        Map<String, Object> search = new HashMap<String, Object>();
        search.put("key_", "system.uname");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("history", 1);
        params.put("filter", filter);
        params.put("search", search);

        //item列表
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "item.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        JSONObject jsonParam = (JSONObject) JSON.toJSON(map);
        JSONObject jsonObj = HttpRequestUtils.httpPost(URL, jsonParam, false, false);

        JSONArray jsonArray = jsonObj.getJSONArray("result");

        String uname = null;
        for(Object obj : jsonArray){
            JSONObject _json = (JSONObject) obj;
            uname = _json.getString("lastvalue").split(" ")[0];
        }
        return uname;
    }

    /***
     * @Author hanzhongqing
     * @Description //TODO 直接从json 中取值，取不到值默认是0；
     * @Date 17:10 2019/3/31
     * @Param [json]
     * @return java.lang.String
     **/
    public static String getZabbixValueFromZabbixKey(JSONObject _json) {
        String value = _json.getString("lastvalue");
        return value;
    }

    private static void setAuth() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", USERNAME);
        params.put("password", PASSWORD);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "user.login");
        map.put("params", params);
        map.put("auth", null);
        map.put("id", 0);

        JSONObject jsonParam = (JSONObject) JSON.toJSON(map);
        JSONObject json = HttpRequestUtils.httpPost(URL, jsonParam, false, false);

        AUTH = json.getString("result");
    }

    private static String getAuth() {
        if (AUTH == null) {
            setAuth();
        }
        return AUTH;
    }
}
